let utils = {}
utils.scrollTop = function (callback) {
    // 页面总高
    var totalH = document.body.scrollHeight || document.documentElement.scrollHeight;
    // 可视高
    var clientH = window.innerHeight || document.documentElement.clientHeight;
    var result = {}
    window.addEventListener('scroll', function (e) {
        // 计算有效高
        var validH = totalH - clientH
        // 滚动条卷去高度
        var scrollH = document.body.scrollTop || document.documentElement.scrollTop
        // 百分比
        result.percentage = (scrollH / validH * 100).toFixed(2)
        result.scrollH = scrollH;
        callback && callback(result)
    })
}

utils.gobackTop = function () {
    let distance = document.documentElement.scrollTop || document.body.scrollTop;
    let step = distance / 50;
    let total = 0;
    if (total < distance) {
        let newTotal = distance - total;
        step = newTotal / 50;
        smoothUp();
    }
    function smoothUp () {
        if (distance > 1) {
            distance -= step;
            document.body.scrollTop = distance;
            document.documentElement.scrollTop = distance;
            setTimeout(smoothUp, 10);
        } else {
            document.body.scrollTop = 1;
            document.documentElement.scrollTop = 1;
        }
    }
}

utils.setlocStore = function (key, obj) {
    if (!navigator.cookieEnabled || typeof window.localStorage == 'undefined') {
        return false;
    }
    localStorage.setItem(key, JSON.stringify(obj));
    return true;
}

utils.getLocStore = function (key) {
    if (!navigator.cookieEnabled || typeof window.localStorage == 'undefined') {
        return false;
    }
    var str = localStorage.getItem(key);
    if (!str) {
        return false;
    }
    return JSON.parse(str);
}

utils.formatDate = function (time) {
    return new Date(time).toLocaleDateString().replaceAll('/', '-') || new Date(time).toLocaleDateString().split('/').join('-')
}

export default utils
